package array;

// 二分查找
public class BinarySearch {
    public static void main(String[] args) {
        int[] array = {-1,0,3,5,9,12};
        int target = 2;
        int position = -1;
        position = binarySearch(array, target);
        if (position == -1) {
            System.out.println("Element not found");
        }
        else {
            System.out.println("Element found at position:" + position);
        }
    }

    public static int binarySearch(int[] arr, int target) {
        int left = 0;
        int right = arr.length - 1;
        while(left <= right) {
            int mid = (left + right) / 2;
            if(arr[mid] == target) {
                return mid;
            }
            else if(arr[mid] < target){
                left = mid+1;
            }
            else{
                right = mid-1;
            }
        }
        return -1;
    }
}
